package com.his.his_system.common.handler;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.his_system.common.util.JwtUtil;
import com.his.his_system.common.util.RedisCache;
import com.his.his_system.domain.DzmHisMember;
import com.his.his_system.domain.LoginUser;
import com.his.his_system.mapper.DzmHisMemberMapper;
import com.his.his_system.service.DzmHisMemberService;
import com.his.his_system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class AuthenticationSuccess implements AuthenticationSuccessHandler {
    @Autowired
    DzmHisMemberMapper dzmHisMemberMapper;

    @Autowired
    RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        DzmHisMember userDetails =(DzmHisMember) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展
        String jwt = JwtUtil.createJWT(userDetails.getUsername(),JwtUtil.JWT_TTL);
        HashMap<Object, Object> resutlMap = new HashMap<>();
        resutlMap.put("token",jwt);
        resutlMap.put("code","20000");
        resutlMap.put("msg","登录成功");

        redisCache.setCacheObject("login:" + userDetails.getUsername(), userDetails);

        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSONUtil.toJsonStr(resutlMap));
    }
}
